package game;

import java.util.Random;

public class Game {
	private Player player1, player2;
	private Console console;
	private Random rand;	
	
	public Game(Console con)
	{
		player1 = null;
		player2 = null;
		console = con;
		rand = new Random();		
	}
	
	public void init()
	{
		console.show(GameMessages.ENTERFIRSTPLAYER);
		player1 = new Player(console.readLine());
		console.show(GameMessages.ENTERSECONDPLAYER);
		player2 = new Player(console.readLine());
	}
	
	public void play()
	{
		while ( player1.getAccumulatedPoints() < 3000 && player2.getAccumulatedPoints() < 3000)
		{		
			makeTurnOfPlayer(player1);
			makeTurnOfPlayer(player2);
		}
	}

	private void makeTurnOfPlayer(Player thePlayer) {
		int points;
		Shot shot = new Shot(rand);
		
		console.show( GameMessages.BEGINTURN );
		console.show( thePlayer.getPlayerName());
		console.show(GameMessages.PRESS_ENTER);
		console.readLine();
		points = doShot(shot);
		
		if ( points >= 300 )
		{			
			GameMessages.showGottenPoints(thePlayer.getPlayerName(), points, console);
			
			boolean canThrowAgain = true;
			boolean wantThrowAgain = true;
			int before, after;
			
			wantThrowAgain = askForNewThrow(shot);
			
			while ( shot.getAvailableDices() > 0 && canThrowAgain && wantThrowAgain )
			{
				before = shot.getAvailableDices();				
				points += points = doShot(shot);
				after = shot.getAvailableDices();
				
				GameMessages.showGottenPoints(thePlayer.getPlayerName(), points, console);				
				if ( before == after )
					canThrowAgain = false;
				else				
					wantThrowAgain = askForNewThrow(shot);				
			}
			
			if (canThrowAgain)
			{
				thePlayer.accumulate(points);
				GameMessages.showAcumulatedPoints(thePlayer.getPlayerName(), thePlayer.getAccumulatedPoints(), console);
			}
			else
				console.show(GameMessages.LOSE_EVERITHING);
		}
		else
			GameMessages.showNoPoints(points, console);
	}

	private int doShot(Shot shot) {
		shot.doShot();
		
		return shot.getScore();
	}

	private boolean askForNewThrow(Shot shot) {
		boolean wantThrowAgain = true;
		
		String resp;
		if ( shot.getAvailableDices() > 0) 
		{
			console.show(GameMessages.ASKFORNEWTHROW);
			resp = console.readLine();
			
			if (resp.equals("N"))
				wantThrowAgain = false;
		}
		return wantThrowAgain;
	}
	
	public void finish()
	{
		if ( player1.getAccumulatedPoints() > player2.getAccumulatedPoints() )
			GameMessages.showWinner(player1.getPlayerName(), console);
		else if ( player1.getAccumulatedPoints() < player2.getAccumulatedPoints() )
			GameMessages.showWinner(player2.getPlayerName(), console);
		else
			console.show(GameMessages.DRAW);	
	}
}
